package com.hitqz.robot.biz.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hitqz.robot.biz.mapper.RobotGroupMapper;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.api.business.entity.RobotGroupEntity;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.biz.mapper.RobotMapper;
import com.hitqz.robot.common.security.service.RobotUser;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 机器人管理表
 *
 * @author robot
 * @date 2024-06-06 15:18:09
 */
@Service
@AllArgsConstructor
public class RobotServiceImpl extends ServiceImpl<RobotMapper, RobotEntity> implements RobotService {


	private final RobotMapper robotMapper;

	private final RobotGroupMapper robotGroupMapper;


	@Override
	public List<Tree<Long>> selectTree(RobotUser user) {
		List<RobotGroupEntity> groups = robotGroupMapper.selectList(Wrappers.emptyWrapper());
		List<String> robotSns = null;

		Map<Integer, String> groupMap = groups.stream().collect(Collectors.toMap(RobotGroupEntity::getId, RobotGroupEntity::getName));
		// 权限内部门
        List<String> finalRobotSns = robotSns;
        List<TreeNode<Long>> collect = groups.stream()
				.map(group -> {
					TreeNode<Long> treeNode = new TreeNode();
					treeNode.setId((long)-group.getId());
					treeNode.setParentId(0L);
					treeNode.setName(group.getName());
					treeNode.setWeight(group.getId());
					// 有权限不返回标识
					Map<String, Object> extra = new HashMap<>(8);
					List<RobotEntity> robotEntities = robotMapper.selectList(Wrappers.<RobotEntity>lambdaQuery().eq(RobotEntity::getGroupId, group.getId()));
					if (finalRobotSns !=null && !finalRobotSns.isEmpty()){
						robotEntities = robotEntities.stream().filter(f -> finalRobotSns.contains(f.getRobotSn())).toList();
					}
					List<TreeNode<Long>> childrenNode = robotEntities.stream().map(f -> {
								f.setGroupName(groupMap.get(f.getGroupId()));
								TreeNode<Long> children = new TreeNode();
								children.setId(Long.valueOf(f.getId()));
								children.setParentId((long)-f.getGroupId());
								children.setName(f.getRobotName());
								children.setWeight(f.getId());
								return children;
							}
					).collect(Collectors.toList());
					extra.put("children", childrenNode);
					treeNode.setExtra(extra);
					return treeNode;
				})
				.collect(Collectors.toList());

		return TreeUtil.build(collect, 0L);
	}

	@Override
	public RobotEntity selectByRobotSn(String robotSn) {
		return baseMapper.selectOne(Wrappers.<RobotEntity>lambdaQuery().eq(RobotEntity::getRobotSn, robotSn));
	}
}